package org.kwisatz.proxybot.filters;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.kwisatz.proxybot.FilterAdapter;
import org.kwisatz.proxybot.Message;
import org.kwisatz.proxybot.Toolkit;

public class Topic extends FilterAdapter
{	
	private final static String COMMAND="!topic ";
	private Map<String, Collection<String>> requests =
		new HashMap<String, Collection<String>>();
	
	@Override
	public String handleClientLine(String line, Message message)
	{
		if("PRIVMSG".equals(message.getCommand()) &&
			message.getEndOfMsg().startsWith(COMMAND))
		{
			String channel = message.getCmdParam();
			String nick = message.getEndOfMsg().substring(COMMAND.length()); 
			synchronized (this)
			{
				Collection<String> c = requests.get(channel);
				if(c == null)
				{
					c = new ArrayList<String>();
					requests.put(channel, c);
					context.getServer().println("TOPIC "+channel);
				}
				c.add(nick);				
			}
		}
		return line;
	}
	
	@Override
	public String handleServerLine(String line, Message message)
	{
		if("332".equals(message.getCommand()))
		{
			String cmdParam = message.getCmdParam();
			String channel = cmdParam.substring(cmdParam.indexOf(' ')+1);
			String topic = message.getEndOfMsg();
			synchronized (this)
			{
				Collection c = requests.get(channel);
				if (c != null)
				{
					PrintWriter pw = Toolkit.channelWriter(context, channel);
					for (Object aC : c)
					{
						String nick = (String) aC;
						pw.println(nick + "> " + topic);
					}
					requests.remove(channel);
				}
			}
		}
		return line;
	}
}
